Imports MindFusion.Diagramming

Public Class frmMainForm

#Region "Attributes"
#Region "Private attributes"
    Private MbReadyForUse As Boolean = False 'indicates proper creation or first initialization of form
    Private WithEvents MoApplicationFile As ClsApplicationFile 'file of application (EXE file)
    Private WithEvents MoUserSettingsFile As ClsUserSettingsFile 'user settings file
    Private WithEvents MoLogFile As ClsLogFile 'log file
    Private MoDScomponents As amod2.DsComponents = New amod2.DsComponents 'DS with components
    Private WithEvents MoApplicationPaths As ClsApplicationPaths 'paths to core files (form templates, Components.xml, ...)
    Private MbWasApplicationLoadedProperly As Boolean = False 'if application was loaded properly (all files objects, XMLs,...)
#End Region
#End Region
#Region "Constructors & Init"
    Public Sub New()
        ' This call is required by the Windows Form Designer.

        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.


        '**********************************************************************
        '!!! registering of my class for serialization, XML save/load,...
        Diagram.RegisterItemClass(GetType(ClsMMContainerNode), "ClsMMContainerNode", 1)
        Diagram.RegisterItemClass(GetType(ClsMMLinkNode), "ClsMMLinkNode", 1)
        Diagram.RegisterItemClass(GetType(ClsMMNoteNode), "ClsMMNoteNode", 1)
        Diagram.RegisterItemClass(GetType(ClsMMTableNode), "ClsMMTableNode", 1)
        Diagram.RegisterItemClass(GetType(ClsMMModuleNode), "ClsMMModuleNode", 1)
        Diagram.RegisterItemClass(GetType(ClsMMActivityNode), "ClsMMActivityNode", 1)
        Diagram.RegisterItemClass(GetType(ClsMMActorNode), "ClsMMActorNode ", 1)
        Diagram.RegisterItemClass(GetType(ClsMMSystemBoundaryNode), "ClsMMSystemBoundaryNode", 1)
        Diagram.RegisterItemClass(GetType(ClsMMNodeForNewLink), "ClsMMNodeForNewLink", 1)
        Diagram.RegisterItemClass(GetType(ClsMMTextNode), "ClsMMTextNode", 1)
        '!!! registering of my class for serialization, XML save/load,...
        '**********************************************************************

        '**********************************************************************
        InitControl()
        '**********************************************************************
    End Sub
    'setting form settings before its using
    Private Function InitControl() As GeActionResult
        SetReadyForUse(False) 'disabling usercontrol
        Try
            RibbonControl.TransparentEditors = True 'VERY IMPORTANT!!!
            StartPosition = FormStartPosition.CenterParent
            Size = New Size(900, 700)
            MinimumSize = New Size(700, 400)
            ShowInTaskbar = True
            ShowIcon = True
            Icon = ConvertImageToIcon(imlFormImages.Images("FORMICON"))
            Text = "???"

            ucnDesktop.Dock = DockStyle.Fill

            SetReadyForUse(True) 'enabling usercontrol
            Return GeActionResult.kkOk
        Catch ex As Exception
            LogEventFromException(ex, , , )
            Return GeActionResult.kkError
        End Try
    End Function
#End Region
#Region "Properties"
#Region "Public properties"
    Public ReadOnly Property ApplicationFile() As ClsApplicationFile
        Get
            Return MoApplicationFile
        End Get
    End Property
    Public ReadOnly Property UserSettingsFile() As ClsUserSettingsFile
        Get
            Return MoUserSettingsFile
        End Get
    End Property
    Public ReadOnly Property LogFile() As ClsLogFile
        Get
            Return MoLogFile
        End Get
    End Property
    Public ReadOnly Property ApplicationPaths() As ClsApplicationPaths
        Get
            Return MoApplicationPaths
        End Get
    End Property
    Public ReadOnly Property DScomponents() As amod2.DsComponents
        Get
            Return MoDScomponents
        End Get
    End Property
#End Region
#End Region
#Region "Events handler"
#Region "frmMainForm - Events handler"
    'loading of frmMainForm
    Private Sub MainForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If InitializeApplication() = GeActionResult.kkOk Then
            MbWasApplicationLoadedProperly = True
            SetSettingsBeforeApplicationStarts()
            ProcessApplicationArguments()
        Else
            'closing application after unsuccessful initialization
            MbWasApplicationLoadedProperly = False
            Me.Close()
        End If
    End Sub
    'closing application
    Private Sub MainForm_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        Dim LbCancelClosing As Boolean = False

        If MbWasApplicationLoadedProperly Then
            'if application was loaded properly then check if its allowed to close application
            LbCancelClosing = Not CanExitApplication()

            If Not LbCancelClosing Then
                SaveUserSettingsToFile()
            End If
        Else
            'if application was NOT loaded properly then close it directly without any checking
            LbCancelClosing = False
        End If

        If Not LbCancelClosing Then
            LogEvent("--------------------------------------------------", False, False)
            LogEvent(IIf(MbWasApplicationLoadedProperly = True, GetTodaysDateTimeString() & " *** UKONCENIE APLIKACIE ***", GetTodaysDateTimeString() & " *** PREDCASNE UKONCENIE APLIKACIE ***"), False, False)
            LogEvent("--------------------------------------------------", False, False)
            LogEvent("****************************************************************************************************", False, False)

            FinishApplication()
        End If

        e.Cancel = LbCancelClosing
    End Sub
#End Region
#Region "RibbonControl - Events handler"
    Private Sub RibbonControl_ApplicationButtonClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles RibbonControl.ApplicationButtonClick
        frmAbout.ShowDialog()
    End Sub
#End Region
#Region "DOCASNE/POVODNE"
    '' '' '' '' ''#Region "txtInPlaceEditor - Events handler"
    '' '' '' '' ''    'keypress on txtInPlaceEditor
    '' '' '' '' ''    Private Sub txtInPlaceEditor_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtInPlaceEditor.KeyPress
    '' '' '' '' ''        Debug.Print("txtInPlaceEditor_KeyPress")

    '' '' '' '' ''        Select Case Asc(e.KeyChar)
    '' '' '' '' ''            Case 13
    '' '' '' '' ''                'ENTER = accept changes
    '' '' '' '' ''                Me.txtInPlaceEditor.Tag = CBool("TRUE") 'saving value needed in DestroyEditControl sub
    '' '' '' '' ''                Me.fcDiagramView.EndEdit(True) 'it doesnt matter on "accept" parameter because Im using my own DevExpress EditControl; http://mindfusion.eu/Forum/YaBB.pl?board=fcnet_disc;action=display;num=1208266554
    '' '' '' '' ''            Case 27
    '' '' '' '' ''                'ESC = reject changes
    '' '' '' '' ''                Me.txtInPlaceEditor.Tag = CBool("FALSE") 'saving value needed in DestroyEditControl sub
    '' '' '' '' ''                Me.fcDiagramView.EndEdit(False) 'it doesnt matter on "accept" parameter because Im using my own DevExpress EditControl; http://mindfusion.eu/Forum/YaBB.pl?board=fcnet_disc;action=display;num=1208266554
    '' '' '' '' ''        End Select
    '' '' '' '' ''    End Sub
    '' '' '' '' ''    'lost focus on txtInPlaceEditor
    '' '' '' '' ''    Private Sub txtInPlaceEditor_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtInPlaceEditor.LostFocus
    '' '' '' '' ''        Debug.Print("txtInPlaceEditor_LostFocus")
    '' '' '' '' ''        Me.fcDiagramView.EndEdit(True) 'it doesnt matter on "accept" parameter because Im using my own DevExpress EditControl; http://mindfusion.eu/Forum/YaBB.pl?board=fcnet_disc;action=display;num=1208266554
    '' '' '' '' ''    End Sub
    '' '' '' '' ''#End Region
    '' '' '' '' ''#Region "UcnVisualPropertiesOfItemUC - Events handler"
    '' '' '' '' ''    'accepting changes after editing visual  properties of item
    '' '' '' '' ''    Private Sub UcnVisualPropertiesOfItemUC_MMValueChanged(ByVal TypeOfPropertyOfItem As UcnPropertiesOfItem.GeTypeOfPropertyOfItem, ByVal Value As Object) Handles UcnVisualPropertiesOfItemUC.MMValueChanged
    '' '' '' '' ''        Debug.Print("UcnVisualPropertiesOfItemUC_ValueChanged")

    '' '' '' '' ''        Dim LeResult As GeActionResult = GeActionResult.kkOk
    '' '' '' '' ''        Dim LoItem As DiagramItem = Me.fcDiagram.ActiveItem

    '' '' '' '' ''        If LoItem IsNot Nothing Then
    '' '' '' '' ''            Select Case LoItem.GetType.Name
    '' '' '' '' ''                ' '' ''Case "ClsMMTableNode"
    '' '' '' '' ''                ' '' ''    Dim LoTable As ClsMMTableNode = CType(LoItem, ClsMMTableNode)
    '' '' '' '' ''                ' '' ''    Select Case TypeOfPropertyOfItem
    '' '' '' '' ''                ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkT_GroupAppearanceSettings
    '' '' '' '' ''                ' '' ''            'do nothing
    '' '' '' '' ''                ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkT_CaptionColor
    '' '' '' '' ''                ' '' ''            LoTable.CaptionColor = CType(Value, Color)
    '' '' '' '' ''                ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkT_RowsColor
    '' '' '' '' ''                ' '' ''            LoTable.TextColor = CType(Value, Color)
    '' '' '' '' ''                ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkT_Brush
    '' '' '' '' ''                ' '' ''            LoTable.Brush = CType(Value, LinearGradientBrush)
    '' '' '' '' ''                ' '' ''        Case Else
    '' '' '' '' ''                ' '' ''            LeResult =GeActionResult.kkError 
    '' '' '' '' ''                ' '' ''            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - ClsMMTableNode")
    '' '' '' '' ''                ' '' ''    End Select
    '' '' '' '' ''                ' '' ''    fcDiagram.Invalidate(LoTable.GetRepaintRect(False))

    '' '' '' '' ''                Case "ClsMMLinkNode"
    '' '' '' '' ''                    Dim LoLink As ClsMMLinkNode = CType(LoItem, ClsMMLinkNode)
    '' '' '' '' ''                    Select Case TypeOfPropertyOfItem
    '' '' '' '' ''                        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkL_GroupAppearanceSettings
    '' '' '' '' ''                            'do nothing
    '' '' '' '' ''                        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkL_CaptionColor
    '' '' '' '' ''                            LoLink.TextColor = CType(Value, Color)
    '' '' '' '' ''                        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkL_Pen
    '' '' '' '' ''                            Dim LoPen As Pen = CType(Value, Pen)
    '' '' '' '' ''                            LoLink.Pen.Color = LoPen.Color
    '' '' '' '' ''                            LoLink.Pen.Width = LoPen.Width
    '' '' '' '' ''                        Case Else
    '' '' '' '' ''                            LeResult = GeActionResult.kkError
    '' '' '' '' ''                            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - ClsMMLinkNode")
    '' '' '' '' ''                    End Select
    '' '' '' '' ''                    ' '' ''Case "ClsMMContainerNode"
    '' '' '' '' ''                    ' '' ''    Dim LoContainer As ClsMMContainerNode = CType(LoItem, ClsMMContainerNode)
    '' '' '' '' ''                    ' '' ''    Select Case TypeOfPropertyOfItem
    '' '' '' '' ''                    ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkC_GroupAppearanceSettings
    '' '' '' '' ''                    ' '' ''            'do nothing
    '' '' '' '' ''                    ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkC_CaptionColor
    '' '' '' '' ''                    ' '' ''            LoContainer.CaptionColor = CType(Value, Color)
    '' '' '' '' ''                    ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkC_Brush
    '' '' '' '' ''                    ' '' ''            LoContainer.Brush = CType(Value, LinearGradientBrush)
    '' '' '' '' ''                    ' '' ''        Case Else
    '' '' '' '' ''                    ' '' ''            LeResult =GeActionResult.kkError 
    '' '' '' '' ''                    ' '' ''            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - ClsMMContainerNode")
    '' '' '' '' ''                    ' '' ''    End Select
    '' '' '' '' ''                Case "ClsMMNoteNode"
    '' '' '' '' ''                    Dim LoShapeNode As ClsMMNoteNode = CType(LoItem, ClsMMNoteNode)
    '' '' '' '' ''                    Select Case TypeOfPropertyOfItem
    '' '' '' '' ''                        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkC_GroupAppearanceSettings
    '' '' '' '' ''                            'do nothing
    '' '' '' '' ''                        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkS_Brush
    '' '' '' '' ''                            LoShapeNode.Brush = CType(Value, LinearGradientBrush)
    '' '' '' '' ''                        Case Else
    '' '' '' '' ''                            LeResult = GeActionResult.kkError
    '' '' '' '' ''                            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - ClsMMNoteNode")
    '' '' '' '' ''                    End Select
    '' '' '' '' ''                Case Else
    '' '' '' '' ''                    LeResult = GeActionResult.kkError
    '' '' '' '' ''                    Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - LoItem.GetType.Name")
    '' '' '' '' ''            End Select
    '' '' '' '' ''        Else
    '' '' '' '' ''            LeResult = GeActionResult.kkError
    '' '' '' '' ''            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - LoItem = Nothing")
    '' '' '' '' ''        End If

    '' '' '' '' ''        If LeResult = GeActionResult.kkOk Then MoAmodFile.FileWasModified = True
    '' '' '' '' ''    End Sub
    '' '' '' '' ''#End Region
    '' '' '' '' ''#Region "UcnPropertiesOfItemUC - Events handler"
    '' '' '' '' ''    'accepting changes after editing properties of item
    '' '' '' '' ''    Private Sub UcnPropertiesOfItemUC_MMValueChanged(ByVal Column As DevExpress.XtraGrid.Columns.GridColumn, ByVal NewValue As Object, ByVal OldValue As Object) Handles UcnPropertiesOfItemUC.MMValueChanged
    '' '' '' '' ''        MoAmodFile.FileWasModified = True

    '' '' '' '' ''        Try
    '' '' '' '' ''            Select Case Column.Caption
    '' '' '' '' ''                Case "Nazov unitu"
    '' '' '' '' ''                    CType(Me.fcDiagram.ActiveItem, ClsMMContainerNode).Caption = CStr(NewValue)
    '' '' '' '' ''                Case "Nazov tabulky"
    '' '' '' '' ''                    CType(Me.fcDiagram.ActiveItem, ClsMMTableNode).Caption = CStr(NewValue)
    '' '' '' '' ''                    MoAmodFile.Trigger_TablesUpdateTableNameAfterAppTableName(CStr(NewValue))
    '' '' '' '' ''                    MoAmodFile.Trigger_HierarchyUpdateParentTableAfterAppTableName(NewValue, OldValue)
    '' '' '' '' ''                Case "Support tabulka"
    '' '' '' '' ''                    CType(Me.fcDiagram.ActiveItem, ClsMMTableNode).MMIsSupportTable = CBool(NewValue)
    '' '' '' '' ''            End Select
    '' '' '' '' ''        Catch ex As Exception
    '' '' '' '' ''            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_MMValueChanged")
    '' '' '' '' ''        End Try
    '' '' '' '' ''    End Sub
    '' '' '' '' ''#End Region
    '' '' '' '' ''#Region "Panels + buttons - Events handler"
    '' '' '' '' ''#Region "ImageListBoxControls for panels - Events handler"
    '' '' '' '' ''    'canceling secondary operation
    '' '' '' '' ''#End Region
#End Region
#End Region
#Region "Subs"
    'sets MbReadyForUse attribute and sets Enable property of form
    Private Sub SetReadyForUse(ByVal IbValue As Boolean)
        MbReadyForUse = IbValue
        Me.Enabled = IbValue 'enabling form
    End Sub
    'finishing application (closing Log file,...)
    Private Sub FinishApplication()
        MoLogFile.CloseFile()
    End Sub
#End Region
#Region "Functions"
    'checking existence of required files and initializing application before apllication starts
    Private Function InitializeApplication() As GeActionResult
        Dim LsErrortext As String = ""

        'setting paths
        Dim LsApplicationPath As String = Application.ExecutablePath
        Dim LsLogFilePath As String = IO.Path.Combine(IO.Path.GetDirectoryName(LsApplicationPath), "Log.txt")
        Dim LsUserSettingsPath As String = IO.Path.Combine(IO.Path.GetDirectoryName(LsApplicationPath), "Data\UserSettings.xml")

        '*** MoLogFile *** - opening or creating Log file
        Try
            'opening file
            MoLogFile = New ClsLogFile(LsLogFilePath)
            If MoLogFile.OpenFile() <> GeActionResult.kkOk Then Throw New Exception("Log subor nie je mozne najst a vytvorit!")

            'writing facts to Log file
            LogEvent("--------------------------------------------------", False, False)
            LogEvent(GetTodaysDateTimeString() & " *** START APLIKACIE ****", False, False)
            LogEvent("", False, False)
            LogEvent("Subor aplikacie: " & LsApplicationPath, False, False)
            LogEvent("Subor uzivatelskych nastaveni: " & LsUserSettingsPath, False, False)
            LogEvent("Subor LOG: " & LsLogFilePath, False, False)
            LogEvent("--------------------------------------------------", False, False)
        Catch ex As Exception
            LogEventFromException(ex)
        End Try
        '*** MoLogFile***

        '*** MoApplicationFile *** - opening application file
        Try
            MoApplicationFile = New ClsApplicationFile(LsApplicationPath)
            If MoApplicationFile.StateOfFile = GeFileState.kkNotInit Then
                LsErrortext = LsErrortext & " Chyba pri spustani EXE suboru aplikacie!"
            End If
        Catch ex As Exception
            LogEventFromException(ex)
        End Try
        '*** MoApplicationFile ***

        '*** MoUserSettingsFile *** - opening or creating User Settings file
        Try
            'creating path + file on disk if doesnt exist
            'opening file
            MoUserSettingsFile = New ClsUserSettingsFile(LsUserSettingsPath)
            If LoadUserSettingsFromFile() <> GeActionResult.kkOk Then LsErrortext = LsErrortext & " Chyba pri otvarani suboru nastaveni!"
        Catch ex As Exception
            LogEventFromException(ex)
        End Try
        '*** MoUserSettingsFile ***

        '*** MoApplicationPaths *** - setting paths to core files (form templates, Components.xml, ...)
        MoApplicationPaths = New ClsApplicationPaths
        MoApplicationPaths.TemplatesDir = IO.Path.Combine(IO.Path.GetDirectoryName(LsApplicationPath), "Data\Templates")
        MoApplicationPaths.FormTemplatesDir = IO.Path.Combine(MoApplicationPaths.TemplatesDir, "Form Templates")
        MoApplicationPaths.ComponentsXMLpath = IO.Path.Combine(MoApplicationPaths.FormTemplatesDir, "Components.xml")
        MoApplicationPaths.FormsExportSettings = IO.Path.Combine(MoApplicationPaths.FormTemplatesDir, "FormsExportSettings.ini")
        '*** MoApplicationPaths *** 

        '*** MoComponents *** - opening XML with components needed in properties of table (component in row) and for generating formulars - buttons, grid,...
        Try
            MoDScomponents.ReadXml(MoApplicationPaths.ComponentsXMLpath, XmlReadMode.IgnoreSchema)
        Catch ex As Exception
            LsErrortext = LsErrortext & " Chyba pri nacitavani komponentov poloziek do gridu!"
            LogEventFromException(ex)
        End Try
        '*** MoComponents ***

        'show error message if needed
        If LsErrortext <> "" Then LogEvent(LsErrortext)

        Return GeActionResult.kkOk
        'TODO stopnutie aplikacie pri vaznej chybe!
    End Function
    'setting settings before apllication starts
    Private Function SetSettingsBeforeApplicationStarts() As GeActionResult
        Try
            'initialization of desktop for the first usage (setting ucnTabControl, menu & toolbars, some default settings...)
            Dim LoAction As ClsAction = New ClsAction(GeAction.kkSetDesktopForFirstUsage)
            Dim LeResult As GeActionResult = ucnDesktop.Execute(LoAction)

            Return LeResult
        Catch ex As Exception
            LogEventFromException(ex, , , )
            Return GeActionResult.kkError
        End Try
    End Function
    'process application arguments
    Private Function ProcessApplicationArguments() As GeActionResult
        Try
            Dim LeResult As GeActionResult = GeActionResult.kkOk

            If Environment.GetCommandLineArgs.Count > 1 Then

                Dim LsPathArgument As String = Environment.GetCommandLineArgs(1) 'significant argument

                If LsPathArgument <> "" Then
                    'opening aMod solution
                    Dim LoAction As ClsAction = New ClsAction(GeAction.kkaModSolutionOpenFile)
                    LoAction.SetData(LsPathArgument, "AMODSOLUTIONFILEPATH")
                    LeResult = ucnDesktop.Execute(LoAction)
                Else
                    Debug.Print("Aplikacia je spustana bez parametrov.")
                End If
            End If

            Return LeResult
        Catch ex As Exception
            LogEventFromException(ex, , , )
            Return GeActionResult.kkError
        End Try
    End Function
    'saving user settings to file
    Private Function SaveUserSettingsToFile() As GeActionResult
        Try
            Return MoUserSettingsFile.SaveFile()
        Catch ex As Exception
            LogEventFromException(ex, , , )
            Return GeActionResult.kkError
        End Try
    End Function
    'loading user settings from file
    Private Function LoadUserSettingsFromFile() As GeActionResult
        Try
            Return MoUserSettingsFile.OpenFile()
        Catch ex As Exception
            LogEventFromException(ex, , , )
            Return GeActionResult.kkError
        End Try
    End Function
    'performs actions before closing application
    'returns value - true = application can be closed otherwise false
    Private Function CanExitApplication() As Boolean
        Dim LoAction As ClsAction = New ClsAction(GeAction.kkCloseTab)
        Dim LeResult As GeActionResult = GeActionResult.kkOk

        LoAction.SetData(False, "ASKFORCLOSINGPROJECT")
        LeResult = ucnDesktop.ucnTabControlUC.MainTabPage.ucnDiagramCanvasAdvanced.Execute(LoAction)

        Return LeResult = GeActionResult.kkOk
    End Function
#End Region

End Class